<template>
  <div>
    <page-view :show-pagesize="false">
      <template #option>
        <div class="btn-box">
          <el-button type="primary" @click="add">新增</el-button>
          <el-button :disabled="selection.length == 0" type="primary" @click="setting">设置必填项</el-button>

        </div>

      </template>

      <template #form>

        <SearchForm :data-form="formInline" @on-search="getList" @onReset="getList">
          <el-form-item prop="feeTypeName" label-width="73px">
            <el-input v-model="formInline.feeTypeName" placeholder="请输入类型名称" clearable />
          </el-form-item>
        </SearchForm>
      </template>
      <template #table="tableScope">
        <PubilcTable :showIndex="true" :showSelect="true" :table-data="tableData" :tableHeight="tableScope.tableHeight"
          :list-config="FEE_TYPE_CONFIG" :page-data="pageData" @on-action="onAction"
          :translateTextDeal="translateTextDeal" @on-selectChange="checkAllChange" :loading="loading">

          <template v-slot:iconUrl>
            <el-table-column width="100" label="类型图标" prop="iconUrl">
              <template v-slot="{ row }">
                <svg-icon :name="String(row.iconName)" style="font-size:30px"
                  :style="{ color: row.iconColor ? row.iconColor : '#7F7F7F' }" />
              </template>
            </el-table-column>
          </template>
        </PubilcTable>

      </template>

    </page-view>
    <addOrEdit :dialogVisible="dialogVisible" v-if="dialogVisible" :type="type" @handleClose="handleClose"
      :dataForm="dataForm" @on-update="onSearch" :invoiceTypeOptions="invoiceTypeOptions"></addOrEdit>

    <SettingRequired ref="settingRef" @refresh="settingRefresh" />
  </div>
</template>
<script  setup >

import { FEE_TYPE_CONFIG, STATUS_LIST, EXPORT_OPTIONS } from '../Common/config'
import { ElMessage, ElMessageBox } from 'element-plus'
import { statusText } from '@/util/index'
import api from '@/api'
import addOrEdit from './addOrEdit.vue'
import SettingRequired, { requiredList } from './SettingRequired.vue'

const settingRef = ref()

const $router = useRouter()
const formInline = ref({
  feeTypeName: ''
})

const tableData = ref([])
const dataForm = ref({
  typeStatus: true,
  typeName: '',
  iconUrl: '',
  iconColor: '#7F7F7F',
  typeCode: '',// 科目编码
  iconName: '',
  companies: '',
  invoiceType: [],
  allowImport: '',
})

const type = ref('add')

const dialogVisible = ref(false)

const pageData = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const loading = ref(false)

const selection = ref([])

const invoiceTypeOptions = ref([])

const invoiceTypeSaveOptions = ref([])

onMounted(() => {

  getCanUseInvoiceType()
})


// 可用发票类型
const getCanUseInvoiceType = () => {
  api.publicApi.canUseInvoiceType().then(res => {
    res = res.map(item => {
      return {
        label: item.message,
        value: item.value
      }
    })
    invoiceTypeOptions.value = [{ label: '全部', value: 'all' }, ...res]
    invoiceTypeSaveOptions.value = res
    getList()
  })
}
const onSearch = () => {
   pageData.value.pageNum = 1
  formInline.value.feeTypeName = ''
  getList()

}

// 获取列表数据
const getList = () => {

  const parms = {
    ...pageData.value,
    ...formInline.value
  }
  loading.value = true
  api.feeConfig.feeTypeList(parms).then(res => {
    loading.value = false

    try {
      console.log(res, 'resss')
      const { list, total } = res
      pageData.value.total = total

      list.forEach(item => {
        let arr = item['iconUrl'].split("_")
        item['iconName'] = arr[0]
        item['iconColor'] = arr[1]
        if (typeof item.invoiceType == 'string' && item.invoiceType != '') {
          let typeList = item.invoiceType.split(",")
          if (typeList.length == invoiceTypeSaveOptions.value.length) {
            item.invoiceTypeText = '全部'
          } else {
            let textArr = []
            typeList.forEach(itemTwo => {
              textArr.push(statusText(invoiceTypeSaveOptions.value, itemTwo))
            })
            item.invoiceTypeText = textArr.join("、")
          }
        }

        if (item.validateField) {
          let validateFields = item.validateField.split(',')
          let arr = []
          validateFields.forEach(tempItem => {
            let findItem = requiredList.find(required => required.value == tempItem)
            findItem && arr.push(findItem.label)
          })

          item.validateFieldLabel = arr.join('、')
        }

      })
      tableData.value = list

    } catch (error) {
      loading.value = false
    }



  })

}




const delRow = (row) => {
  ElMessageBox.confirm(
    '您确定要进行删除操作吗?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      api.feeConfig.feeTypeDelete({ id: row.id }).then(res => {
        onSearch()
        ElMessage.success('操作成功')
      })
    })

}

// 编辑
const editRow = (row) => {
  let rows = { ...row }
  if (rows.invoiceType) rows.invoiceType = rows.invoiceType.split(",")
  rows.allowImport = String(rows.allowImport)
  dataForm.value = rows
  type.value = 'edit'
  dialogVisible.value = true
}

// 复制
const copyTypeHandle = (row) => {
  let rows = { ...row }
  if (rows.invoiceType) rows.invoiceType = rows.invoiceType.split(",")
  rows.typeCode = ''
  rows.allowImport = String(rows.allowImport)
  dataForm.value = rows
  type.value = 'copy'
  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false

}

const toEditForm = (row) => {
  $router.push({ path: '/design/expense-designer', query: { feeTypeId: row.id } })
}

// 列表操作 分页
const onAction = ([item, row]) => {
  console.log(item, row)
  const obj = {
    'del': delRow,
    'copy': copyTypeHandle,
    'edit': editRow,
    'editForm': toEditForm,
    'pageNum': getList,
    'pageSize': onSearch

  }
  if (typeof item === 'string') {
    pageData.value[item] = row
    obj[item]()
  } else {
    obj[item.alias](row)
  }

}
// 显示新增弹框
const add = () => {
  dataForm.value = {
    typeStatus: true,
    typeName: '',
    iconUrl: '',
    iconColor: '#7F7F7F',
    iconName: '',
    typeCode: ''
  }
  type.value = 'add'
  dialogVisible.value = true

}



const translateTextDeal = (item, val) => {

  let text = ''
  if (item.alias == "allowImport") text = statusText(EXPORT_OPTIONS, val)
  if (item.alias == "typeStatus") text = statusText(STATUS_LIST, val)
  return text

}


const setting = () => {
  settingRef.value.show(selection.value.map(item => item.id))
}


const checkAll = ref(false)

const checkAllChange = (list) => {
  console.log(list)
  selection.value = list
}


const settingRefresh = () => {

  getList()
}

</script>
<style lang="scss" scoped>
.table-main {
  overflow-x: scroll;
}

.table-box {
  position: relative;
  width: 100%;
  overflow: hidden;

  thead {
    // position: absolute;
    // top: 0;
    // left: 0;
    // right: 0;
    height: 45px;
    width: 100%;
    background: #f8fafc;

    tr {
      display: flex;


      th {
        text-align: left;
        color: #000000;
        font-size: 15px;
        padding: 12px 16px;
        float: left;


      }
    }
  }

  tbody {
    position: absolute;
    top: 45px;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    overflow-y: auto;
    overflow-x: hidden;

    tr {
      cursor: pointer;
      display: flex;
      border-bottom: 1px solid #ebeef5;

      .cell {
        display: flex;
        align-items: center;
      }

      td {
        float: left;
        text-align: left;
        align-items: center;
        display: flex;
        color: rgb(96, 98, 102);
        font-size: 15px;
        padding: 12px 16px;

        min-height: 46px;

        p {
          margin: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
      }
    }
  }
}

.prompt {
  margin-top: 8px;
  font-size: 14px;
  // margin-left: 10px;
}
</style>
